﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public partial class LegalEntities : ISetChangedUser, IGetNamesValues, IGetKeyValue
    {
        #region Implementation of ISetChangedUser

        /// <summary>
        /// Установка пользователя, который сделал изменение
        /// </summary>
        /// <param name="userLogin">Логин пользователя</param>
        public void SetChangedUser(string userLogin)
        {
            if (string.IsNullOrEmpty(userLogin))
                throw new Exception("Логин пользователя не должен быть пустым");

            IdUser = userLogin;
        }

        #endregion

        private List<Turnovers> _sales;


        /// <summary>
        /// Главный адрес
        /// </summary>
        public Addresses PrimaryAddress
        {
            get
            {
                if (Addresses.Count == 0)
                    return null;
                Addresses address = Addresses.FirstOrDefault(add => add.IsPrimary != null && (bool) add.IsPrimary);

                if (address == null)
                {
                    address = Addresses.First();
                    address.IsPrimary = true;
                    DB.Save();
                }


                return address;
            }
        }


        /// <summary>
        /// Идентификатор региона профайн
        /// </summary>
        public int IdProfineRegion
        {
            get
            {
                foreach (Addresses item in Addresses)
                {
                    return item.IdProfineRegion;
                }
                if (Customers != null && Customers.IdprofineRegion != null) return (int) Customers.IdprofineRegion;

                return 0;
            }
        }


        /// <summary>
        /// Продажи юридического лица
        /// </summary>
        public List<Turnovers> Sales
        {
            get
            {
                if (_sales == null)
                {
                    var col = new TurnoversCollection();
                    _sales = col.GetSalesByIdLegalEntity(IdLegalEntity);
                }
                return _sales;
            }
        }

        /// <summary>
        /// Название клиента
        /// </summary>
        public string CustomerName
        {
            get { return Customers.Name; }
        }

        public int? CustomerSAPNumber
        {
            get { return Customers.NumberInSAP; }
        }

        /// <summary>
        /// Первый оборото клиента
        /// </summary>
        public Turnovers FirstTurnover
        {
            get
            {
                IOrderedEnumerable<Turnovers> tempCol = from turnover in Turnovers
                                                        orderby turnover.Period ascending
                                                        select turnover;
                Turnovers fTurnover = tempCol.FirstOrDefault();

                return fTurnover;
            }
        }


        /// <summary>
        /// Первый оборото клиента
        /// </summary>
        public v_TrueTurnovers FirstTrueTurnover
        {
            get
            {
                return DB.TrueTurnovers.OrderBy(c => c.Period).FirstOrDefault(c => c.IdLegalEntity == IdLegalEntity);

                //  return null;
            }
        }

        /// <summary>
        /// Города юридических лиц одной строкой
        /// </summary>
        public string CitiesStr
        {
            get { return Cities.Aggregate("", (current, item) => current + " " + item); }
        }

        /// <summary>
        /// Список городов
        /// </summary>
        public List<string> Cities
        {
            get
            {
                var result = new List<string>();

                foreach (Addresses item in Addresses)
                {
                    if (item.CityLocalised != null && !result.Contains(item.CityLocalised))
                    {
                        result.Add(item.CityLocalised);
                    }
                }

                return result;
            }
        }


        /// <summary>
        /// Организационно правовая форма юридического лица
        /// </summary>
        public string OwnerShipPatternLocalized
        {
            get
            {
                if (IdOwnershipPattern > 0)
                {
                    if (OwnershipPatterns != null) return OwnershipPatterns.LocalizedName;
                }
                return "";
            }
        }

        public string PrimaryCity
        {
            get
            {
                if (PrimaryAddress != null)
                    if (PrimaryAddress.Settlements != null) return PrimaryAddress.Settlements.NameLocalized;
                return "-";
            }
        }

        /// <summary>
        /// Менеджер
        /// </summary>
        public string Manager
        {
            get { return Customers.Manager; }
        }


        /// <summary>
        /// Название региона профайн по-русски
        /// </summary>
        public string profineRegionRu
        {
            get { return Customers.ProfineRegionNameRu; }
        }


        public string PrimaryRegion
        {
            get
            {
                if (PrimaryAddress != null)
                    return PrimaryAddress.ProfineRegionNameLocalized;
                return "-";
            }
        }

        /// <summary>
        /// Локализованная строка областей юр. лица
        /// </summary>
        public string RegionsLocalizedString
        {
            get { return Regions.Aggregate("", (current, item) => item != null ? current + item.NameRu + ", " : null); }
        }

        /// <summary>
        /// Области, в которых находится клиент
        /// </summary>
        public List<Regions> Regions
        {
            get
            {
                var result = new List<Regions>();

                foreach (Addresses item in Addresses)
                {
                    if (!result.Contains(item.Region))
                    {
                        result.Add(item.Region);
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// Локализованное название региона профайн
        /// </summary>
        public string ProfineRegionNameLocalized
        {
            get
            {
                if (PrimaryAddress != null)
                    return PrimaryAddress.ProfineRegionNameLocalized;

                foreach (Addresses address in Addresses)
                {
                    return address.ProfineRegionNameLocalized;
                }
                return Customers.ProfineRegionNameLocalized;
            }
        }


        private int _sequentalNumber;

        /// <summary>
        /// Клиентский номер клиента
        /// </summary>
        public int SequentialNumber
        {
            get
            {
                if (_sequentalNumber == 0)
                   
            //    var firstOrDefault = DB.Entities.LegalEntities.FirstOrDefault(c => c.IdLegalEntity == IdLegalEntity);
            //    if (firstOrDefault != null)
            //        return
            //            firstOrDefault.Customers.
            //                SequentialNumber;

            //    return 0;
                _sequentalNumber= Customers != null ? Customers.SequentialNumber : 0;

                return _sequentalNumber;
            }
        }

        public AgreementElements ActiveAgreementElement
        {
            get { return AgreementElements.FirstOrDefault(c => c.IsActive); }
        }

        #region Implementation of IGetNamesValues

        /// <summary>
        /// Получение списка имён
        /// </summary>
        /// <returns>Список имён</returns>
        public List<string> GetNamesValues()
        {
            //  var col = new CustomersNamesCollection();
            var result = new List<string>();

            result.Add(Name);
            // result.Add(CustomerName);

            return result;
        }

        #endregion

        #region Implementation of IGetKeyValue

        /// <summary>
        /// Получение ключего значения элемента
        /// </summary>
        /// <returns>Ключевое значение</returns>
        public int GetKeyValue()
        {
            return IdLegalEntity;
        }

        #endregion
    }
}